#!/usr/bin/env python

import optparse
import urllib
import zipfile
import os.path
import shutil
from tempfile import mkstemp

def main():
	usage = "usage: %prog [-U URL]"
	parser = optparse.OptionParser(usage=usage)
	parser.add_option("-U", "--url", dest="srcfile", 
				default="http://bm2.googlecode.com/files/BombusMod596.jar", 
				type="string", help="specify file to extract")

	parser.add_option("-t", "--type", dest="buildtype", 
				default="fullbuild", 
				type="string", help="specify type of build")

	(options, args) = parser.parse_args()
	srcfile = options.srcfile
	print "Downloading file %s ..." % srcfile
	tmp = mkstemp()
	urllib.urlretrieve(srcfile, tmp[1])
	Zip = zipfile.ZipFile(tmp[1], "r")
	rootdir = os.path.join("distfiles", options.buildtype)
	if os.path.exists(rootdir):
		shutil.rmtree(rootdir)
	print "Extracting to %s..." % rootdir
	Zip.extractall(rootdir)	
	print "Cleaning..."
#	os.remove(tmp[1]) // TODO: free used file 
	rmfolders = ["images", "sounds", "lang", "skins", "smiles"]
	for folder in rmfolders:
		rmfolder = os.path.join(rootdir, folder)
		if os.path.exists(rmfolder):
			shutil.rmtree(rmfolder)
	iconfile =  os.path.join(rootdir, "_icon.png")
	if os.path.exists(iconfile):
		os.remove(iconfile)
	print "OK\n"
	

if __name__=="__main__":
	main()